<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NSpace vertical :size="14">
      <NGrid :x-gap="14" :y-gap="14" responsive="screen" item-responsive>
        <NGi span="24 s:24 m:4">
          <NCard title="组织树" :bordered="false" class="h-100% sm:flex-1-hidden card-wrapper">
            <!-- 组织树 -->
            <OrgTree :treeData="state.treeData" @handle-nodeClick="handleNodeClick"/>
          </NCard>
        </NGi>

        <NGi span="24 s:24 m:20">
          <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
            <PositionSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
            <NCard title="职位列表" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
              <template #header-extra>
                <TableHeaderOperation
                  v-model:columns="columnChecks"
                  :disabled-delete="checkedRowKeys.length === 0"
                  :loading="loading"
                  @add="handleAdd"
                  @delete="handleBatchDelete"
                  @refresh="getData"
                />
              </template>
              <NDataTable
                v-model:checked-row-keys="checkedRowKeys"
                :columns="columns"
                :data="data"
                size="small"
                :scroll-x="962"
                :loading="loading"
                remote
                :row-key="row => row.id"
                :pagination="mobilePagination"
                :max-height="450"
                :single-line="false"
                striped
                class="sm:h-full"
              />
            </NCard>
            <PositionEditModal v-model:visible="visible" :operate-type="operateType" :row-data="editingData" @submitted="getDataByPage"/>
          </div>
        </NGi>

      </NGrid>
    </NSpace>
  </div>
</template>

<script setup lang="tsx">
import {defineAsyncComponent, onMounted, reactive, Ref, ref, toRefs} from 'vue'
import { NButton, NPopconfirm,NTag } from 'naive-ui';
import { useTable, useTableOperate } from '@/hooks/common/table';
import {useBoolean} from '@sa/hooks';
import { orgTree } from '@/service/api/org-api';
import {positionPage,positionDelete} from '@/service/api/position-api'
import PositionSearch from "@/views/org/position/modules/position-search.vue";
import PositionEditModal, {type OperateType} from "@/views/org/position/modules/position-edit-modal.vue";
import {positionCategoryRecord} from "@/constants/common";
import SvgIcon from "@/components/custom/svg-icon.vue";
const OrgTree = defineAsyncComponent(() => import('@/components/common/org-tree.vue'))

const {bool: visible, setTrue: openModal} = useBoolean();

const state = reactive({
  treeData: [] as Api.SystemManage.OrgTreeType[],
})

// 初始化加载
onMounted(() => {
  getOrgTree()
})

// 获取组织树数据
async function getOrgTree() {
  const {data} = await orgTree()
  if (Array.isArray(data)) {
    state.treeData = data
  }
}
// 点击组织的回调
const handleNodeClick = (context: number) => {
  searchParams.orgId = context
  getDataByPage();
}
// 批量删除
async function handleBatchDelete() {
  const result: Api.Common.DeleteParams[] = checkedRowKeys.value.map(key => ({id: key}));
  await positionDelete(result)

  await onBatchDeleted();
}
// 删除
async function handleDelete(id: number) {
  let params: Api.Common.DeleteParams[] = [{id: id}]
  await positionDelete(params)
  await onDeleted();
}

const operateType = ref<OperateType>('add');
const editingData: Ref<number | null> = ref(null);
// 新增
function handleAdd() {
  operateType.value = 'add';
  openModal();
}

// 编辑
function edit(id: number) {
  operateType.value = 'edit';
  editingData.value = id;
  openModal();
}

const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: positionPage,
  showTotal: true,
  apiParams: {
    pageNumber: 1,
    pageSize: 10,
    searchKey: null,
    category:null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 30
    },
    {
      key: 'index',
      title: '序号',
      align: 'center',
      width: 50
    },
    {
      key: 'name',
      title: '职位名称',
      align: 'center',
      width: 100
    },
    {
      key: 'category',
      title: '分类',
      align: 'center',
      width: 100,
      render: row => {
        if (row.category === null) {
          return null;
        }

        const tagMap: Record<Api.SystemManage.PositionCategory, NaiveUI.ThemeColor> = {
          HIGH: 'success',
          MIDDLE: 'warning',
          LOW: 'info',
        };

        const label = positionCategoryRecord[row.category];

        return <NTag type={tagMap[row.category]}>{label}</NTag>;
      }
    },
    {
      key: 'sortCode',
      title: '排序',
      align: 'center',
      width: 100
    },
    {
      key: 'createUserName',
      title: '创建人',
      align: 'center',
      width: 100
    },
    {
      key: 'createTime',
      title: '创建时间',
      align: 'center',
      width: 100
    },
    {
      key: 'operate',
      title: '操作',
      align: 'center',
      width: 120,
      render: row => (
        <div class="flex-center gap-8px">
          <NButton quaternary type="primary" size="small" onClick={() => edit(row.id)}>
            <SvgIcon icon='mdi:lead-pencil' class="text-icon" />
            编辑
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
            {{
              default: () => '确认删除吗？',
              trigger: () => (
                <NButton quaternary type="error" size="small">
                  <SvgIcon icon='mdi:delete' class="text-icon" />
                  删除
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ]
});

const {
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
} = useTableOperate(data, getData);

</script>

<style scoped>

</style>
